import { createStore } from 'redux'
interface IState {
    totalPrice: number,
    allCheck: boolean,
    groups: any
}
let initState = {
    totalPrice: 0,
    allCheck: false,
    groups: [],

}
function getTotalPrice(state: any) {
    return state.groups.reduce((prev: any, item: any) => {
        let groupPrice = item.list.reduce((prePrice: any, current: any) => {
            let price = current.num * current.price
            return prePrice + price
        }, 0)
        return prev + groupPrice
    }, 0)
}
function reducer(state = initState, action: any) {
    state = JSON.parse(JSON.stringify(state))
    switch (action.type) {
        case "INIT_DATA":
            state.groups = action.car.groups

            return state
        case "CHNAGE_NUM": {
            let { num, groupKey, itemKey } = action
            state.groups[groupKey].list[itemKey].num = num
            // 计算总价
            state.totalPrice = getTotalPrice(state)
            return { ...state }
        }
        case "CHANGE_CHECK":  
            let { isCheck, groupKey, itemKey } = action
            if (groupKey === undefined && itemKey === undefined) {
                state.allCheck = isCheck
                state.groups.forEach((groups: any) => {
                    groups.groupCheck = isCheck;
                    groups.list.forEach((item: any) => {
                        item.itemCheck = isCheck;
                    })
                })
            }

            state.totalPrice = getTotalPrice(state)
            return state 
        default:
            return state
    }
}
const store = createStore(reducer)
export default store